package com.game.gateway.net.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kodgames.core.event.EventManager;
import com.game.core.net.common.RemoteNode;
import com.game.core.net.handler.AbstractConnectionHandler;
import com.game.core.service.ServiceContainer;
import com.game.core.session.SessionService;
import com.game.gateway.event.login.ITerminateEvent;

public class CSConnectionHandler extends AbstractConnectionHandler<Object> 
{
	static private Logger logger = LoggerFactory.getLogger(CSConnectionHandler.class);
	@Override
    public void handleConnectionActive(RemoteNode remoteNode)
    {
	    logger.info("Connection active. Remote Client Address:{}", remoteNode.getAddress());
//		// 连接数限制, 这个必须在第一个判断
//		// if(connectionThreshold.incrementAndGet() >= CommonConstants.MAX_CONNECTION_CLIENT_COUNT)
//		if (getConnectionCount() >= CommonConstants.MAX_CONNECTION_CLIENT_COUNT)
//		{
//			logger.info("client connection is too much to do it. current connection is " + getConnectionCount() + ", remoete node is " + remoteNode.getAddress());
//			remoteNode.close();
//			return;
//		}
		SessionService ss = ServiceContainer.getInstance().getPublicService(SessionService.class);
		if (ss != null)
			ss.addSession(remoteNode);
		else
			logger.error("add session failed. can't find session service. remote node is " + remoteNode.getAddress().toString());
		//TODO
		//加入踢人逻辑
    }

	@Override
    public void handleConnectionInactive(RemoteNode remoteNode)
    {
		logger.info("Connection inactive. Remote Client Address:{}", remoteNode.getAddress());  
		try
		{
			if(remoteNode.getID() != 0)
			{
				ITerminateEvent event = EventManager.getInstance().createEvent(ITerminateEvent.class, true);
				event.flush(event.onTerminate(remoteNode));	
			}
		}
		catch(Exception exception)
		{
			logger.error("handleConnectionInactive: exception arise. accountID is {} ,error={}", remoteNode.getAccountID(), exception);
		}
		finally 
		{
			ServiceContainer.getInstance().getPublicService(SessionService.class).RemoveSession(remoteNode);
		}
    }

	@Override
    public Object getMessageKey(RemoteNode remoteNode)
    {
	    return remoteNode.getAccountID();
    }
}
